import re
import threading
import os
import urllib

import language

class Updater(threading.Thread):
    
    __version__ = '2.2'
    
    _baseFolder = None
    _urlUpdate = None
    _notif = None
    _numVersion = ''
    _actual = [0, 0]
    _arch = ''
    _path = ''
    
    def __init__(self):
        threading.Thread.__init__(self)
        self._lang = language.setup()
        self.execute = None
        
    def configure(self, bf, uu, noti, dire, ar):
        Updater._baseFolder = bf
        Updater._urlUpdate = uu
        Updater._notif = noti
        Updater._arch = ar
        Updater._path = dire
        try:
            version = open(Updater._path + 'version', 'r')
        except IOError:
            f = open(Updater._path + 'version', 'w')
            f.write(Updater.__version__)
            f.close()
            version = open(Updater._path + 'version', 'r')
        value = version.read()
        value = value.split('.')
        Updater._actual = [int(value[0]), int(value[1].replace('\n',''))]
        
    def run(self):
        self.execute()
        
    def check(self):
        web = self._read_page(Updater._urlUpdate).split('\n')
        pat = re.compile('^\d+.+')
        if pat.match(web[0]):
            nums = web[0].split('.')
            version = [int(nums[0]), int(nums[1])]
            Updater._newVersion = ((Updater._actual[0] == version[0] and Updater._actual[1] < version[1])
                        or (Updater._actual[0] < version[0]))
            if Updater._newVersion:
                Updater._numVersion = web[0].replace('\n', '')
        if Updater._newVersion:
            Updater._notif.show_message(self._lang['newVersion'], Updater._numVersion)
        
    def update(self):
        web = self._read_page(Updater._urlUpdate).split('\n')
        pat = re.compile('^\d+.+')
        toUpdate = []
        for f in web:
            if not pat.match(f):
                toUpdate.append(f)
        fileName = ''
        for fileIns in toUpdate:
            fileName = '/' + os.path.basename(fileIns.replace('\n', ''))
            if Updater._arch in fileName:
                code = self._read_page(fileIns)
                f = open(Updater._baseFolder + fileName, 'w')
                f.write(code)
                f.close()
                break
        f = open(Updater._path + 'version', 'w')
        f.write(Updater._numVersion)
        f.close()
        Updater._notif.show_message(self._lang['updated'], Updater._baseFolder + fileName)
                
    def _read_page(self, link):
        page = urllib.urlopen(link)
        return page.read()
